var {getDb} = require("./init");
var MyMap = require('lodash.map')
const AV = getDb()

function dao(name) {
    var Obj = AV.Object.extend(name);
    this.__name__ = name
    this.obj = new Obj();
    this.objQuery = new AV.Query(name);

    this.getObj = () => {
        return this.obj
    }
    this.select = (options) => {
        if (!options.id) {
            throw "options.id is required";
            return false;
        }
        this.obj.id = options.id;
        return this.objQuery.get(options.id)
    }

    this.insert = (options) => {
        var self = this
        if (options.id) {
            self.obj.id = options.id;
        }
        MyMap(options, (value, key) => {
            self.obj.set(key, value)
        })
        return self.obj.save()
    }
    this.update = (id, options2) => {
        var self = this
        if (!id) {
            throw "id is required";
            return false;
        }
        this.obj.id = id;
        MyMap(options2, (value, key) => {
            self.obj.set(key, value)
        })
        return self.obj.save()
    }
    this.delete = (id) => {
        var obj = AV.Object.createWithoutData(this.__name__, id);
        return obj.destroy(id)
    }
    return this
}


module.exports = dao